
`ifndef __bus_timer_v__
`define __bus_timer_v__

module bus_timer #(
    parameter SYS_FREQ = 12000000  
)(
    input clk , 
    input rst_n , 

    input  wire [7:0]  m_dat_i  , 
    output wire [7:0]  m_dat_o  , 
    input  wire [7:0]  m_adr_i , 
    input  wire        m_wen_i 
) ;

function integer clog2(input integer c) ; 
    for(clog2=0;|c ; clog2=clog2+1)
        c=c>>1;
endfunction 


localparam MAX = SYS_FREQ/1000 - 1 ;

localparam  N = clog2(MAX)  ;

reg [31:0] tik ;
reg [N : 0] cnt ;

always @(posedge clk ) begin
    if(~rst_n) begin
        tik <= 'd0 ;
        cnt <= MAX;
    end else begin
        // if(m_wen_i) begin
        //     case(m_adr_i)
        //         8'h00: begin 
        //             led <= m_dat_i ;
        //             $display("%t ns | led=%d" , $time , m_dat_i) ;
        //         end 
        //     endcase 
        // end

        if(~|cnt)begin
            tik <= tik +1'b1 ;
            cnt <= MAX ;
        end else begin
            cnt <= cnt - 1'b1 ;
        end
    end
end

assign m_dat_o = 
    m_adr_i==8'h0 ? tik[7:0] :
    m_adr_i==8'h1 ? tik[15:8] :
    m_adr_i==8'h2 ? tik[23:16] :
    m_adr_i==8'h3 ? tik[31:24] : 8'h00 ;



endmodule 

`endif 